from django import forms
from .models import RegisterModel


class RegisterForm(forms.Form):
    role_choices = (
        ('student', '学生'),
        ('company', '企业'),
        ('admin', '管理员'),
    )
    role = forms.ChoiceField(
        choices=role_choices,

    )
    username = forms.CharField(max_length=20, min_length=2, error_messages={
        'required': '用户名不能为空',
        'max_length': '用户名不能超过20个字符',
        'min_length': '用户名不能少于2个字符'
    })
    password = forms.CharField(max_length=20, min_length=4, widget=forms.PasswordInput, error_messages={
        'required': '密码不能为空',
        'max_length': '密码不能超过20个字符',
        'min_length': '密码不能少于4个字符'
    })
    identify_password = forms.CharField(max_length=20, widget=forms.PasswordInput, error_messages={
        'invalid': '密码不一致',
    })
    def clean_username(self):
        username = self.cleaned_data.get('username')
        if RegisterModel.objects.filter(username=username).exists():
            raise forms.ValidationError('该用户名已被注册')
        return username

    def clean(self):
        password = self.cleaned_data.get('password')
        identify_password = self.cleaned_data.get('identify_password')
        if password != identify_password:
            raise forms.ValidationError('两次密码不一致')
        return self.cleaned_data



class LoginForm(forms.Form):
    role_choices = (
        ('student', '学生'),
        ('company', '企业'),
        ('admin', '管理员'),
    )
    role = forms.ChoiceField(
        choices=role_choices,
        error_messages={
            'required': '请选择角色'
        }
    )
    username = forms.CharField(max_length=20, error_messages={
        'required': '用户名不能为空',
        'max_length': '用户名不能超过20个字符'
    })
    password = forms.CharField(max_length=20, widget=forms.PasswordInput, error_messages={
        'required': '密码不能为空',
        'max_length': '密码不能超过20个字符'
    })
